//
// Created by zyw on 23-2-23.
//

#ifndef CM_THREAD_TASK_MANAGER_H
#define CM_THREAD_TASK_MANAGER_H

#include <list>
#include <iostream>
#include <pthread.h>
#include "CMLock.h"

class CMThreadItem
{
  public:
    CMThreadItem()
    {
        pid = 0;
    }
    pthread_t   pid;
    std::string name;
};

class CMThreadRunImpl
{
  public:
    // 独立线程执行完此函数之后就直接返回
    // 集中线程不定期执行此函数，要求不要执行时间太长，要把机会留给其它线程，只处理简单循环任务
    virtual int run() = 0;

    // 对于独立线程可以不用管
    // 对于集中线程必須要调置，线程执行完了要保证这个返回 true
    virtual bool runDone()
    {
        return false;
    };

    CMThreadItem threadItem;
    int *        p_curThreads;
};

class CMThreadTaskManager
{
  public:
    CMThreadTaskManager(int maxThreads = 10);
    virtual ~CMThreadTaskManager();

    void setMaxThreadsCount(int max)
    {
        maxThreadsSupport = max;
    }

    // impl 必須是通过 new 创建，在执行完之后，本类中会进行销毁
    int addToThread(CMThreadRunImpl *impl, std::string &name, int runAlone = true);
    int addToThread(CMThreadRunImpl *impl, const char *name, int runAlone = true);

    int start();
    int stop();

    void debug();

  protected:
    friend void *thread_run(void *args);

    int runSelf();

    int runInNewThread(CMThreadRunImpl *impl);

  private:
    int                          maxThreadsSupport;
    int                          curThreads;
    pthread_t                    mainPid;
    std::list<CMThreadRunImpl *> threadList;
    std::list<CMThreadRunImpl *> threadAlone;

    std::list<CMThreadRunImpl *> threadListTemp;
    std::list<CMThreadRunImpl *> threadAloneTemp;

    bool   exited;
    CMLock lock;
};

#endif // CM_THREAD_TASK_MANAGER_H
